package su.storage.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.kuakao.core.dto.PagerDTO;
import net.kuakao.core.exception.DataBaseException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import su.base.Constants;
import su.product.dao.IMaterialDAO;
import su.product.dao.IProductDAO;
import su.product.entity.Material;
import su.product.entity.Product;
import su.storage.dao.IStorageMaterialDAO;
import su.storage.dao.IStorageProductDAO;
import su.storage.entity.StorageMaterial;
import su.storage.entity.StorageProduct;
import su.storage.service.StorageService;
import su.tool.SuDateUtils;
import su.user.dao.IUserGhsDAO;
import su.user.entity.UserGhs;

public class StorageServiceImpl implements StorageService {
	
	@Autowired
	private IStorageProductDAO storageProductDAO;

	@Autowired
	private IStorageMaterialDAO storageMaterialDAO;

	@Autowired
	private IProductDAO productDAO;
	
	@Autowired
	private IUserGhsDAO ghsDAO;
	
	@Autowired
	private IMaterialDAO materialDAO;
	//===============产品
	public List<Map<String,String>> getStorageProductsByPage(PagerDTO s){
		List<Map<String,String>> list = null;
		try {
			List<StorageProduct> ps = storageProductDAO.queryByPage(s);
			if(ps==null || ps.isEmpty())return list;
			//设置显示数据
			list = new ArrayList<Map<String,String>>();
			Map<String,String> map;
			String res="";
			UserGhs ghs;
			Material material;
			for(StorageProduct sp : ps){
				map = new HashMap<String,String>();
				map.put("productid", sp.getProductid()+"");
				map.put("productName", sp.getProductName());
				map.put("flowtime", SuDateUtils.getFormatString(sp.getFlowtime(), "yyyy-MM-dd"));
				map.put("flowtype", sp.getFlowtype()+"");
				map.put("flownum", sp.getFlownum()+"");
				//map.put("total", sp.getTotal()+"");
				map.put("ptotal", sp.getPtotal()+"");
				res = "";
				if(sp.getFlowtype()==1){//入库
					if(sp.getBuy()==1){//购买
						res = "单价："+sp.getPrice();
						ghs = ghsDAO.getById(sp.getGhsid());
						if(ghs!=null)res += "，供货商ID："+sp.getGhsid()+"，供货商："+ghs.getGhsname();
					}
					if(sp.getBuy()==2){//非购买
						material = materialDAO.getById(sp.getMaterialid());
						if(material!=null)res="原料ID："+sp.getMaterialid()+"，原料："+material.getMname();
					}
				}
				if(sp.getFlowtype()==2){//出库
					if(StringUtils.isNotBlank(sp.getOrderid())){
						res = "订单号："+sp.getOrderid();						
					}
				}
				if(StringUtils.isNotBlank(sp.getSdesc())){
					if(StringUtils.isNotBlank(res)){
						res += ",";
					}
					res += "备注："+sp.getSdesc();
				}
				map.put("res", res);
				map.put("id", sp.getId()+"");
				list.add(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	
	public StorageProduct getStorageProductById(int id){
		StorageProduct one = null;
		try {
			one = storageProductDAO.getById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return one;
	}

	public void saveStorageProduct(StorageProduct o)throws Exception {
		o.setStatus(Constants.STATUS_ENABLE);
		int pid = o.getProductid();
		if(pid==0){
			throw new DataBaseException("对应产品id为0");
		}
		Product p = productDAO.getById(pid);
		if(p==null){
			throw new DataBaseException("未找到产品信息，产品id为"+pid);
		}
		double addNum=0;
		if(o.getFlowtype() == 1){
			addNum = o.getFlownum();
		}else{
			addNum = (-1)*o.getFlownum();
		}
		double totalNum = p.getTotalnum();//当前存量
		if(o.getId()==0){//添加
			totalNum += addNum;
//			o.setTotal(totalNum);
			o.setCreateTime(new Date());
			storageProductDAO.insert(o);
			//修改产品的库存数量
			productDAO.updateTotalNum(pid, totalNum);
		}else{//修改
			StorageProduct odb = storageProductDAO.getById(o.getId());
			if(odb==null){
				throw new DataBaseException("产品出入库记录未找到，id为"+o.getId());
			}
			double reduceNum = 0;
			if(odb.getFlowtype()==1){//原来是入库
				reduceNum = odb.getFlownum();
			}else{//原来是出库
				reduceNum = (-1)*odb.getFlownum();
			}
			//double oldTotalNum = odb.getTotal();//即时存量
//			oldTotalNum = oldTotalNum - reduceNum + addNum;
//			odb.setTotal(oldTotalNum);
			odb.setBuy(o.getBuy());
			odb.setFlownum(o.getFlownum());
			odb.setFlowtime(o.getFlowtime());
			odb.setFlowtype(o.getFlowtype());
			odb.setGhsid(o.getGhsid());
			odb.setMaterialid(o.getMaterialid());
			odb.setOrderid(o.getOrderid());
			odb.setOuttype(o.getOuttype());
			odb.setPrice(o.getPrice());
			odb.setProductid(pid);
			odb.setSdesc(o.getSdesc());
			odb.setStorage(o.getStorage());
			storageProductDAO.update(odb);
			if(reduceNum != addNum){
				//修改产品库存数量
				totalNum = totalNum - reduceNum + addNum;
				productDAO.updateTotalNum(pid, totalNum);
				//之后的记录都得修改即时存量
				//storageProductDAO.updateTotalAfter(odb.getProductid(),reduceNum-addNum, odb.getCreateTime());
			}
		}
		
	}
	
	public void removeStorageProduct(int id)throws Exception {
		if(id==0){
			throw new DataBaseException("记录id为0");
		}
		StorageProduct sp = storageProductDAO.getById(id);
		if(sp==null){
			throw new DataBaseException("产品出入库记录为空，id为"+id);
		}
		int pid = sp.getProductid();
		Product p = productDAO.getById(pid);
		if(p==null){
			throw new DataBaseException("未找到产品信息，产品id为"+pid);
		}
		double addNum=0;
		if(sp.getFlowtype() == 1){//入库
			addNum = sp.getFlownum();
		}else{//出库
			addNum = (-1)*sp.getFlownum();
		}
		double totalNum = p.getTotalnum();//当前存量
		totalNum -= addNum;
		//删除出入库记录
		storageProductDAO.remove(id);
		//修改产品存量
		productDAO.updateTotalNum(pid, totalNum);
	}

	//==============原料
	public StorageMaterial getStorageMaterialById(int id) {
		StorageMaterial one = null;
		try {
			one = storageMaterialDAO.getById(id);
			if(one==null)return null;
			//供货商
			if(one.getGhsid()!=0){
				UserGhs ghs = ghsDAO.getById(one.getGhsid());
				if(ghs!=null){
					one.setGhsname(ghs.getGhsname());
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return one;
	}

	public List<Map<String, String>> getStorageMaterialsByPage(PagerDTO s) {
		List<Map<String, String>> list = null;
		try {
			List<StorageMaterial> sms = storageMaterialDAO.queryByPage(s);
			if(sms == null || sms.isEmpty())return null;
			//设置显示数据
			list = new ArrayList<Map<String,String>>();
			Map<String,String> map;
			String res="";
			UserGhs ghs;
			for(StorageMaterial sm : sms){
				map = new HashMap<String,String>();
				map.put("materialid", sm.getMaterialid()+"");
				map.put("mname", sm.getMname());
				map.put("flowtime", SuDateUtils.getFormatString(sm.getFlowtime(), "yyyy-MM-dd"));
				map.put("flowtype", sm.getFlowtype()+"");
				map.put("flownum", sm.getFlownum()+"");
				//map.put("total", sm.getTotal()+"");
				map.put("mtotal", sm.getMtotal()+"");
				res = "";
				if(sm.getFlowtype()==1){//入库
					res = "单价："+sm.getPrice();
					ghs = ghsDAO.getById(sm.getGhsid());
					if(ghs!=null){
						res += "，供货商ID："+sm.getGhsid()+"，供货商："+ghs.getGhsname();
					}
				}
				if(sm.getFlowtype()==2){//出库
					
				}
				if(StringUtils.isNotBlank(sm.getSdesc())){
					if(StringUtils.isNotBlank(res)){
						res+=",";
					}
					res += "备注："+sm.getSdesc();
				}
				map.put("res", res);
				map.put("id", sm.getId()+"");
				list.add(map);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	public void saveStorageMaterial(StorageMaterial o) throws Exception {
		o.setStatus(Constants.STATUS_ENABLE);
		//获取原料的当前库存量
		int mid = o.getMaterialid();
		if(mid==0){
			throw new DataBaseException("对应原料id为0");
		}
		Material m = materialDAO.getById(mid);
		if(m==null){
			throw new DataBaseException("对应原料信息为空，原料id为"+mid);
		}
		double addNum = 0;
		if(o.getFlowtype() == 1){//入库
			addNum = o.getFlownum();
		}else{//出库
			addNum = (-1)*o.getFlownum();
		}
		double totalNum = m.getTotalnum();//当前存量
		if(o.getId()==0){//添加
			totalNum += addNum;
			//o.setTotal(totalNum);
			o.setCreateTime(new Date());
			storageMaterialDAO.insert(o);
			//修改原料的库存数量
			materialDAO.updateTotalNum(mid, totalNum);
		}else{//修改
			StorageMaterial odb = storageMaterialDAO.getById(o.getId());
			if(odb==null){
				throw new DataBaseException("原料出入库记录未找到，id为"+o.getId());
			}
			double reduceNum = 0;
			if(odb.getFlowtype()==1){//原来是入库
				reduceNum = odb.getFlownum();
			}else{//原来是出库
				reduceNum = (-1)*odb.getFlownum();
			}
			//double oldTotalNum = odb.getTotal();//即时存量
//			oldTotalNum = oldTotalNum - reduceNum + addNum;
//			odb.setTotal(oldTotalNum);
			odb.setFlownum(o.getFlownum());
			odb.setFlowtime(o.getFlowtime());
			odb.setFlowtype(o.getFlowtype());
			odb.setGhsid(o.getGhsid());
			odb.setOuttype(o.getOuttype());
			odb.setPrice(o.getPrice());
			odb.setSdesc(o.getSdesc());
			odb.setStorage(o.getStorage());
			storageMaterialDAO.update(odb);
			if(reduceNum != addNum){
				//修改原料库存数量
				totalNum = totalNum - reduceNum + addNum;
				materialDAO.updateTotalNum(mid, totalNum);
				//之后的记录都得修改即时存量
				//storageMaterialDAO.updateTotalAfter(odb.getMaterialid(),reduceNum-addNum, odb.getCreateTime());
			}
		}
	}

	public void removeStorageMaterial(int id) throws Exception {
		if(id==0){
			throw new DataBaseException("原料出入库记录id为0");
		}
		StorageMaterial sm = storageMaterialDAO.getById(id);
		if(sm==null){
			throw new DataBaseException("出入库记录为空，id为"+id);
		}
		int mid = sm.getMaterialid();
		Material m = materialDAO.getById(mid);
		if(m==null){
			throw new DataBaseException("对应原料信息为空，原料id为"+mid);
		}
		double addNum = 0;
		if(sm.getFlowtype() == 1){//入库
			addNum = sm.getFlownum();
		}else{//出库
			addNum = (-1)*sm.getFlownum();
		}
		double totalNum = m.getTotalnum();//当前存量
		totalNum -= addNum;
		//删除出入库记录
		storageMaterialDAO.remove(id);
		//修改原料的库存数量
		materialDAO.updateTotalNum(mid, totalNum);
	}

}

